﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HanGu.Services.Interface;
using HanGu.Entity;
using System.Transactions;

namespace HanGu.Services
{
    public class MessageService : BaseService, IMessage
    {

        public List<Message> GetAll()
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                return obj.Message.OrderByDescending(c => c.CreateTime).ToList();
            }
        }

        public List<Message> GetMsgByMemberID(int memberID, List<int> CreatorIDs)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var query = obj.Message.Where(c => 1 == 1);
                var msgIDs = obj.MessageItem.Where(c => c.MemberID == memberID).Select(c => c.MsgID).ToList<int>() ?? new List<int>();
                query = query.Where(c => msgIDs.Contains(c.ID));
                if (CreatorIDs != null && CreatorIDs.Count > 0)
                {
                    query = query.Where(c => c.CreatorID.HasValue && CreatorIDs.Contains(c.CreatorID.Value));
                }
                return query.OrderByDescending(c => c.CreateTime).ToList();
            }
        }

        public List<vwMessage> GetMsgByID(int msgID)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                return obj.vwMessage.Where(c => c.ID == msgID).OrderByDescending(c => c.CreateTime).ToList();
            }
        }

        public List<Message> GetAll(UniversallySearchParam searchparma)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var query = obj.Message.Where(c => 1 == 1);
                if (!string.IsNullOrEmpty(searchparma.Ttile))
                {
                    query = query.Where(c => c.Title.IndexOf(searchparma.Ttile) >= 0 || c.Remark.IndexOf(searchparma.Ttile) >= 0);
                }
                if (searchparma.IntObj2.HasValue && searchparma.IntObj2 != 0)
                {
                    query = query.Where(c => c.MemberID == searchparma.IntObj2);
                }
                if (searchparma.IntObj1 != -1)
                {
                    query = query.Where(c => c.Type == searchparma.IntObj1);
                }
                if (searchparma.StarDateTime.HasValue)
                {
                    query = query.Where(c => c.CreateTime >= searchparma.StarDateTime);
                }
                if (searchparma.EndDateTime.HasValue)
                {
                    query = query.Where(c => c.CreateTime <= searchparma.EndDateTime);
                }
                if (searchparma.SubAssignedIn != null && searchparma.SubAssignedIn.Count > 0)
                {
                    query = query.Where(c => searchparma.SubAssignedIn.Contains(c.CreatorID.Value));
                }
                query = base.Paging<Message, DateTime?>(c => c.CreateTime, query, searchparma.Pagination);
                var messages = query.ToList();
                //foreach (var item in messages)
                //{
                //    SetReciever(obj, item);
                //}
                return messages;
            }
        }

        public Message GetByID(int id)
        {
            using (HaiGuEntities obj = new HaiGuEntities())
            {
                var model = obj.Message.Where(c => c.ID == id).FirstOrDefault();
                if (model != null)
                {
                    var member = obj.MemberInfo.SingleOrDefault(c => c.ID == model.MemberID);
                    if (member != null)
                    {
                        model.MemberName = string.Format("{0}[{1}]", member.RealName, member.ID);
                    }
                    //model = SetReciever(obj, model);
                }
                return model;
            }
        }

        private Message SetReciever(HaiGuEntities obj, Message model)
        {
            try
            {
                var reviceMembers = obj.MemberInfo.Where(m => obj.MessageItem.Where(c => c.MsgID == model.ID).Select(c => c.MemberID).Contains(m.ID)).ToList();
                if (reviceMembers != null)
                {
                    model.ReviceMembers = reviceMembers.Select(c => c.RealName).ToList();
                }
            }
            catch (Exception e)
            {
                base.ExceptionHand(e);
            }
            return model;
        }


        public bool Add(Message model, List<MemberInfo> members = null)
        {
            try
            {
                //using (TransactionScope scope = new TransactionScope())
                {
                    using (HaiGuEntities obj = new HaiGuEntities())
                    {
                        obj.Message.AddObject(model);
                        obj.SaveChanges();

                        if (members != null && members.Count > 0)
                        {
                            //using (HaiGuEntities obj = new HaiGuEntities())
                            {
                                foreach (var item in members)
                                {
                                    var msgItem = new MessageItem();
                                    msgItem.MemberID = item.ID;
                                    msgItem.MsgID = model.ID;
                                    msgItem.Receiver = model.GUID;
                                    obj.MessageItem.AddObject(msgItem);
                                }
                                obj.SaveChanges();
                            }
                        }
                    }
                    //scope.Complete();
                    return true;
                }

            }
            catch (Exception ex) { throw ex; return false; }
        }

        public bool Add(Message model, string memberIDs)
        {
            try
            {
                //using (TransactionScope scope = new TransactionScope())
                {
                    using (HaiGuEntities obj = new HaiGuEntities())
                    {
                        obj.Message.AddObject(model);
                        obj.SaveChanges();

                        if (!string.IsNullOrEmpty(memberIDs))
                        {
                            //using (HaiGuEntities obj = new HaiGuEntities())
                            {
                                foreach (var item in memberIDs.Split(','))
                                {
                                    int memberid = 0;
                                    if (int.TryParse(item, out memberid))
                                    {
                                        var msgItem = new MessageItem();
                                        msgItem.MemberID = memberid;
                                        msgItem.MsgID = model.ID;
                                        msgItem.Receiver = model.GUID;
                                        obj.MessageItem.AddObject(msgItem);
                                    }
                                }
                                obj.SaveChanges();
                            }
                        }
                    }
                    //scope.Complete();
                    return true;
                }

            }
            catch (Exception ex) { throw ex; return false; }
        }

        public bool Update(Message model, List<MemberInfo> members = null)
        {
            try
            {
                //using (TransactionScope scope = new TransactionScope())
                {
                    using (HaiGuEntities obj = new HaiGuEntities())
                    {
                        this.Update<Message>(model);

                        if (members != null && members.Count > 0)
                        {
                            this.Delete<MessageItem>(c => c.MsgID == model.ID);
                            foreach (var item in members)
                            {
                                var msgItem = new MessageItem();
                                msgItem.MemberID = item.ID;
                                msgItem.MsgID = model.ID;
                                msgItem.Receiver = model.GUID;
                                obj.MessageItem.AddObject(msgItem);
                            }
                            obj.SaveChanges();
                        }
                    }
                    //scope.Complete();
                    return true;

                }

            }
            catch (Exception ex) { throw ex; return false; }
        }

        public bool Update(Message model, string memberIDs)
        {
            try
            {
                //using (TransactionScope scope = new TransactionScope())
                {
                    using (HaiGuEntities obj = new HaiGuEntities())
                    {
                        this.Update<Message>(model);

                        if (!string.IsNullOrEmpty(memberIDs))
                        {
                            this.Delete<MessageItem>(c => c.MsgID == model.ID);
                            foreach (var item in memberIDs.Split(','))
                            {
                                int memberid = 0;
                                if (int.TryParse(item, out memberid))
                                {
                                    var msgItem = new MessageItem();
                                    msgItem.MemberID = memberid;
                                    msgItem.MsgID = model.ID;
                                    msgItem.Receiver = model.GUID;
                                    obj.MessageItem.AddObject(msgItem);
                                }
                            }
                            obj.SaveChanges();
                        }
                    }
                    //scope.Complete();
                    return true;

                }

            }
            catch (Exception ex) { throw ex; return false; }
        }

        public bool Delete(int id)
        {
            try
            {
                //using (TransactionScope scope = new TransactionScope())
                //{
                //    this.Delete<Message>(c => c.ID == id);
                //    this.Delete<MessageItem>(c => c.MsgID == id);
                //    scope.Complete();
                //    return true;
                //}
                using (HaiGuEntities obj = new HaiGuEntities())
                {
                    string sql = "Delete from Message where id={0};Delete from MessageItem where MsgID={0};";
                    sql = string.Format(sql, id);
                    obj.ExecuteStoreCommand(sql);
                    return true;
                }
            }
            catch { return false; }
        }

        public bool DeleteMessageItem(int msgID, int memberID)
        {
            try
            {

                using (HaiGuEntities obj = new HaiGuEntities())
                {
                    string sql = "Delete from MessageItem where MsgID={0} and MemberID={1};";
                    sql = string.Format(sql, msgID, memberID);
                    obj.ExecuteStoreCommand(sql);
                    return true;
                }
            }
            catch { return false; }
        }
    }
}
